package com.sth.test3;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.sth.domain.ItemResultEntity;
import com.sth.domain.TestResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author: sitianhong
 * @Description:
 * @Since: create in 2021/11/29 0029 15:58
 */
@Slf4j
public class Processor3 {
    static List<TestResultEntity> allList = new ArrayList<>();
    static List<String> keywordList = Arrays.asList("DDR_A00", "DDR_CB0", "VDD_CPU OF IDDQ", "VDD_SOC OF IDDQ MAX", "VDD_RSM OF IDDQ MAX", "IDDS of DDR_VDDQ ", "IDDS of HT_1V8", "IDDS of HT_VDD",
                                                    "IDDS of PCIE_1V2R", "IDDS of PEST2V5", "IDDS of PEST_1V2T", "IDDS of PLL_CORE_AVDD", "IDDS of PLL_CORE_DVDD", "IDDS of PLL_SATA_AVDD ",
                                                    "IDDS of PLL_SATA_DVDD", "IDDS of RSM2V5", "IDDS of RSM3V3", "IDDS of RTC_2V5", "IDDS of SATA_1V2R", "IDDS of THENS_AVDD", "IDDS of USB_A2V5",
                                                    "IDDS of USB_A3V3", "IDDS of VDDE3V3", "IDDS of VGA_A2V5", "IDDD of VDD_CPU", "IDDD of VDD_SOC", "IDDD of DDR_VDDQ", "IDDD of HT_1V8",
                                                    "IDDD of HT_VDD", "IDDD of PCIE_1V2R", "IDDD of PEST2V5", "IDDD of PEST_1V2T", "IDDD of PLL_CORE_AVDD", "IDDD of PLL_CORE_DVDD",
                                                    "IDDD of PLL_SATA_AVDD", "IDDD of PLL_SATA_DVDD", "IDDD of RSM2V5", "IDDD of RSM3V3", "IDDD of RTC_2V5", "IDDD of SATA_1V2R", "IDDD of THENS_AVDD",
                                                    "IDDD of USB_A2V5", "IDDD of USB_A3V3", "IDDD of VDDE3V3", "IDDD of VDD_RSM", "IDDD of VGA_A2V5", "ACPI_VID0", "DVO_D00", "AC97_SDATAO", "NAND_D0",
                                                    "LPC_AD0", "SPI_SDI", "DDR_A00", "GPIO00", "VGA_VSYNC", "IIC0_SCL", "UART0_TXD", "EJTAG_TDO");

    static String unitRule = "\\d+";
    static String valueRule = "[a-zA-Z]";

    public static void getFilePath(String filePath, String excelName) throws IOException {
        String rootFile = filePath;
        File root = new File(rootFile);
        File[] subFiles = root.listFiles();

        List<String> fileNameList = new LinkedList<>();
        for (File f : subFiles) {
            fileNameList.add(f.getName());
        }

        fileNameList.stream().forEach(item -> {
            readText(filePath + "\\" + item, item);
        });

        // 写入excel
        excelData(allList, filePath, excelName);
    }

    private static void readText(String filePath, String fileName) {
        List<String> efficientDataList = new ArrayList<>();

        // 数据收集
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            String str = "";
            fis = new FileInputStream(filePath);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            while ((str = br.readLine()) != null) {
                if (!StringUtils.contains(str, "#devices")
                        && !StringUtils.contains(str, "ERCY ALL") && !StringUtils.contains(str, "nannS")&& !StringUtils.contains(str, "MIN")) {
                    for (String item : keywordList) {
                        if (StringUtils.contains(str, item)) {
                            efficientDataList.add(str);
                        }
                    }
                }
            }
            processData(efficientDataList, fileName);// 数据处理和存储
        } catch (Exception e) {
            System.out.println("找不到指定文件" + e);
        } finally {
            try {
                br.close();
                isr.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void excelData(List<TestResultEntity> allList, String filePath, String excelName) throws IOException {
        String fileName = filePath + "\\" + excelName + ".xlsx";
        File testFile = new File(fileName);
        if (!testFile.exists()) {
            testFile.createNewFile();// 能创建多级目录
        }
        // 已经采集成功了
        try {
            // 头的策略
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            WriteFont headWriteFont = new WriteFont();
            headWriteFont.setFontHeightInPoints((short) 10);
            headWriteCellStyle.setWriteFont(headWriteFont);
            // 内容的策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            WriteFont contentWriteFont = new WriteFont();
            // 字体大小
            contentWriteFont.setFontHeightInPoints((short) 40);
            contentWriteCellStyle.setWriteFont(contentWriteFont);
            // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
            // 创建文件
            EasyExcel.write(fileName).registerWriteHandler(horizontalCellStyleStrategy).sheet("文件采集数据").doWrite(dataList(allList));
        } catch (Exception e) {
            System.out.println("error-----生成Excel失败!" + e);
        }

    }

    private static List dataList(List<TestResultEntity> allList) {
        List<List<String>> list = new ArrayList<List<String>>();
        allList.stream().forEach(item -> {
            // 没一行数据
            LinkedHashMap<String, LinkedList<ItemResultEntity>> testLineData = item.getTestData();
            testLineData.forEach((k, v) -> {
                List<String> data = new ArrayList<String>();
                data.add(k);// 文件名字
                // 文件数据
                LinkedList<ItemResultEntity> testLineListData = (LinkedList<ItemResultEntity>) v;
                testLineListData.stream().forEach(testItem -> {
                    testItem.getTestName();
                    data.add(testItem.getTestName());
                    data.add(testItem.getTestValue());
                    if (testItem.getTestUnit() != null) {
                        data.add(testItem.getTestUnit());
                    }
                });
                list.add(data);
            });
        });
        return list;
    }

    private static void processData(List<String> efficientDataList, String fileName) {
        //数据处理
        LinkedList<ItemResultEntity> itemResultEntities = new LinkedList<>();// 共41调数据
        AtomicReference<Integer> ddr_a00Integer = new AtomicReference<>(0);
        AtomicReference<Integer> ddr_cb0Integer = new AtomicReference<>(0);

        efficientDataList.forEach(s1 -> {
            String item = s1.replaceAll("\\s{1,}", " ");
            //System.out.println("itme----->" + item);
            if (StringUtils.contains(item, "DDR_A00")) {
                ddr_a00Integer.getAndSet(ddr_a00Integer.get() + 1);
                // 取值第二个 DDR_A00 取值 第一个和第二个
                if (ddr_a00Integer.get() == 2 || ddr_a00Integer.get() == 1) {
                    String[] s = item.split(" "); //
                    ItemResultEntity itemResultEntity = new ItemResultEntity();
                    itemResultEntity.setTestName("DDR_A00");
                    itemResultEntity.setTestValue(s[4]);
                    itemResultEntities.add(itemResultEntity); //2
                }
            } else if (StringUtils.contains(item, "DDR_CB0")) {
                ddr_cb0Integer.getAndSet(ddr_cb0Integer.get() + 1);
                // 取值第二个 DDR_A00 取值 第一个和第二个
                if (ddr_cb0Integer.get() == 3 || ddr_cb0Integer.get() == 4) {
                    String[] s = item.split(" "); //
                    ItemResultEntity itemResultEntity = new ItemResultEntity();
                    itemResultEntity.setTestName("DDR_CB0");
                    itemResultEntity.setTestValue(s[4]);
                    itemResultEntities.add(itemResultEntity); //2
                }
            } else {
                for (String keyword : keywordList) {
                    if (StringUtils.contains(item, keyword)) {
                        if (StringUtils.contains(item, "VDD_CPU OF IDDQ") || StringUtils.contains(item, "VDD_SOC OF IDDQ") || StringUtils.contains(item, "VDD_RSM OF IDDQ")) {
                            String[] s = item.split(" "); //
                            ItemResultEntity itemResultEntity = new ItemResultEntity();
                            itemResultEntity.setTestName(keyword);
                            itemResultEntity.setTestValue(s[5]);
                            itemResultEntities.add(itemResultEntity); //2
                        } else if (StringUtils.contains(item, "of")) {
                            String[] s = item.split(" "); //
                            ItemResultEntity itemResultEntity = new ItemResultEntity();
                            itemResultEntity.setTestName(keyword);
                            itemResultEntity.setTestValue(s[4]);
                            itemResultEntities.add(itemResultEntity); //2
                        } else if (StringUtils.contains(item, "TIME")) {
                            String[] s = item.split(" "); //
                            ItemResultEntity itemResultEntity = new ItemResultEntity();
                            itemResultEntity.setTestName(keyword);
                            String valueAndUnit = s[3].trim();
                            String unit = valueAndUnit.replaceAll(unitRule, "");
                            String value = valueAndUnit.replaceAll(valueRule, "");
                            itemResultEntity.setTestValue(value);
                            itemResultEntity.setTestUnit(unit);
                            itemResultEntities.add(itemResultEntity); //2
                        }

                    }
                }

            }
        });
        //  System.out.println("heelllo");
        TestResultEntity testResultEntity = new TestResultEntity();
        LinkedHashMap<String, LinkedList<ItemResultEntity>> objectObjectLinkedHashMap = new LinkedHashMap<>();
        objectObjectLinkedHashMap.put(fileName, itemResultEntities);
        testResultEntity.setTestData(objectObjectLinkedHashMap);
        allList.add(testResultEntity);
    }
}
